package cn.com.yusys.yusp.admin.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import cn.com.yusys.yusp.commons.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.yusys.yusp.commons.dto.Contr;
import cn.com.yusys.yusp.commons.dto.DataContr;
import cn.com.yusys.yusp.commons.dto.MenuContr;
import cn.com.yusys.yusp.commons.dto.User;
import cn.com.yusys.yusp.commons.security.SecurityUtils;
import cn.com.yusys.yusp.commons.util.CommonUtil;
import cn.com.yusys.yusp.uaa.security.AuthUtils;

/**
 * 用户信息获取客户端.
 * 
 *
 * @author tangxb
 */
@Service
public class UserProviderServiceImpl implements UserProviderService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserProviderServiceImpl.class);
	
	@Autowired
    private UserServicePlus userService;
	
	@Autowired
    private AdminUserService adminUserService;

	@SuppressWarnings("unchecked")
    public List<Contr> getAllContrUrl() {
    	return  (List<Contr>) userService.findAllContrUrl(null);
	}

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public String getUserCode() {
    	Map parsedTokenMap = AuthUtils.getParsedAccessTokenMap();
        String accessToken = AuthUtils.getCurrentUserToken(parsedTokenMap);
        logger.info("getUserCode accessToken: {}", accessToken);
    	String userCode = userService.getUserCode(accessToken);
    	logger.info("getUserCode userCode: {}", userCode);
    	return  userCode;   
	}

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public User getUserInfo(String loginCode, String sysId) {
    	Map parsedTokenMap = AuthUtils.getParsedAccessTokenMap();
        String accessToken = AuthUtils.getCurrentUserToken(parsedTokenMap);
        if (StringUtils.isEmpty(accessToken)) {
            logger.warn("Failed to get user authorization information {}", accessToken);
            return null;
        }else {
            logger.info("userCode: {}", loginCode);
            return userService.getUserInfo(loginCode, sysId, accessToken);
        }
	}


    public MenuContr getMenuandContr(String loginCode, String sysId, String roleId) {
        String accessToken = SecurityUtils.getCurrentUserToken();
        
        //异步加载数据权限
        CompletableFuture.supplyAsync(()->userService.getDataAuth(loginCode,sysId, accessToken));
        
        if (StringUtils.isEmpty(accessToken)) {
            logger.warn("Failed to get user authorization information {}", accessToken);
            return null;
        }else {
            return userService.getMenuandContrByRoleId(loginCode,sysId, accessToken,roleId);
        }
	}

    @SuppressWarnings("unchecked")
	public List<DataContr> getDataAuth(String loginCode, String sysId) {
         String accessToken = SecurityUtils.getCurrentUserToken();
         if (StringUtils.isEmpty(accessToken)) {
             logger.warn("Failed to get user authorization information {}", accessToken);
             return null;
         }else {
             return (List<DataContr>) userService.getDataAuth(loginCode,sysId, accessToken);
         }
	}

    public void cleanAllContrUrlCache() {
    	userService.cleanAllContrUrlCache();
	}

    public void cleanUserInfoCache() {
    	String accessToken = SecurityUtils.getCurrentUserToken();
		userService.cleanUserInfoCache(accessToken);
	}

    public void cleanMenuAndContrCache() {
    	String accessToken = SecurityUtils.getCurrentUserToken();
		userService.cleanMenuAndContrCache(accessToken);
	}

    public void cleanDataContrCache() {
    	String accessToken = SecurityUtils.getCurrentUserToken();
		userService.cleanDataContrCache(accessToken);
	}

    /**
     * 通过机构查询该机构下所有用户
     * 
     * @param orgId
     * @return
     */
    public List<String> queryUserByOrgId( String orgId) {
    	return adminUserService.selectOrgUser(orgId);
	}

    /**
     * 通过机构id查询所属机构下用户信息
     * 
     * @param orgIds
     * @return
     */
    public List<String> queryUserByOrgIds(List<String> orgIds) {
    	return adminUserService.selectOrgsUsers(orgIds);
	}

    /**
     * 通过角色id查询属于该角色的所有用户
     * 
     * @param roleId
     * @return
     */
    public List<String> queryUserByRoleId( String roleId) {
    	return adminUserService.selectRoleUser(roleId);
	}

    /**
     * 通过部门id查询属于该部门下所有的用户信息
     * 
     * @param dutyId
     * @return
     */
    public List<String> queryUserByDutyId( String dutyId) {
    	return adminUserService.selectDutyUser(dutyId);
	}

    /**
     * 通过用户id查询该用户所属机构id
     * 
     * @param userId
     * @return
     */
    public List<String> queryOrgsByUserId(String userId) {
    	return adminUserService.selectUserOrg(userId);
	}

    /**
     * 通过上级机构id查询所有的上级机构id属于该上级机构id
     * 
     * @param upOrgId
     * @return
     */
    public List<String> queryOrgsByUpOrgId( String upOrgId) {
    	return adminUserService.selectUpOrgOrgs(upOrgId);
	}

    /**
     * 根据机构id查询该机构的上级机构
     * 
     * @param orgId
     * @return
     */
    public List<String> queryUpOrgByOrgId( String orgId) {
    	return adminUserService.selectUpOrg(orgId);
	}

    /**
     * 根据用户id查询用户信息
     * 
     * @param userId
     * @return
     */
    public Map<String, Object> queryUserInfoByUserId( String userId) {
    	List<Map<String, Object>> list = adminUserService.selectUserInfo(userId);
        if (CommonUtil.nonNullOrEmpty(list)) {
            return list.get(0);
        }
        return null;
	}

}